package codegenerator;

import java.util.ArrayList;
import java.util.List;

import baytony.util.Util;
import codegenerator.generator.CssGenerator;
import codegenerator.generator.IGenerator;
import codegenerator.generator.XmlGenerator;

public class Executor {
		
	private List<IGenerator> generators;
	private GeneratorHelper helper;
	/**
	 * 不用產生code的table，可在applicationContext.xml設定
	 */
	private List<String> unGenerateTable;
	
	public void setGenerators(List<IGenerator> generators) {
		this.generators = generators;
	}
	
	public void setHelper(GeneratorHelper helper) {
		this.helper = helper;
	}
	
	public void setUnGenerateTable(List<String> unGenerateTable) {
		this.unGenerateTable = unGenerateTable;
	}

	/**
	 * 執行code generator
	 *
	 * @throws CodeGeneratorException
	 */
	public void execute() throws CodeGeneratorException {
		List<TableInfo> tables = helper.getTables();
		tables = this.filterTable(tables);
		for(IGenerator generator : generators) {
			if(generator instanceof XmlGenerator || generator instanceof CssGenerator) {
				TableInfo[] tis = new TableInfo[tables.size()];
				for(int i=0 ; i<tables.size() ; i++) {
					tis[i] = tables.get(i);
				}
				generator.generate(tis);
			}			
			else {
				for(TableInfo table : tables) {
					try {
						generator.generate(table);
					} catch (CodeGeneratorException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
		
	/**
	 * 過濾不用產生的table
	 *
	 * @param tables
	 * @return
	 * @throws CodeGeneratorException
	 */
	public List<TableInfo> filterTable(List<TableInfo> tables) throws CodeGeneratorException {
		if(Util.isEmptyList(tables))
			throw new CodeGeneratorException("No tables in target database");
		if(Util.isEmptyList(unGenerateTable))
			return tables;
		List<TableInfo> removeCollection = new ArrayList<TableInfo>();
		for(TableInfo table : tables) {
			for(String ungenStr : unGenerateTable) {
				if(ungenStr.equals(table.getName())) {
					removeCollection.add(table);
					break;
				}
			}			
		}
		tables.removeAll(removeCollection);
		return tables;
	}
}
